<?php defined("MAIN_DIR") or die("No direct access");

$auto_id = UV::readInt($route->getPath(5));

$edit_error = false;
$cur_error = false;
if (isset($_POST['action']) && $_POST['action'] == "edit")
{
	if (!isset($_POST['RUB']) && !isset($_POST['USD']) && !isset($_POST['EUR']))
		$cur_error = true;
	$bank = filter_var($_POST['bank'],FILTER_SANITIZE_MAGIC_QUOTES);
	$regionally = $route->POST('regionally') ? 1 : 0;
	if ($db->getCell("select `parent` from `bank` where `bank_id` = '$bank' limit 1")) {
		$regionally = 0;
	}
	$name = trim(filter_var($_POST['name'],FILTER_SANITIZE_MAGIC_QUOTES));
	$seller = trim(filter_var($_POST['seller'],FILTER_SANITIZE_MAGIC_QUOTES));
	$vehicle_type = trim(filter_var($_POST['vehicle_type'],FILTER_SANITIZE_MAGIC_QUOTES));
	$initial_fee = trim(filter_var($_POST['initial_fee'],FILTER_SANITIZE_MAGIC_QUOTES));
	$delivery_commission = trim(filter_var($_POST['delivery_commission'],FILTER_SANITIZE_MAGIC_QUOTES));
	$service_commission = trim(filter_var($_POST['service_commission'],FILTER_SANITIZE_MAGIC_QUOTES));
	$early_repayment = 0;
	if (isset($_POST['early_repayment']))
		$early_repayment = 1;
	$er_commission = trim(filter_var($_POST['er_commission'],FILTER_SANITIZE_MAGIC_QUOTES));
	$insurance = trim(filter_var($_POST['insurance'],FILTER_SANITIZE_MAGIC_QUOTES));
	$insurance_in_amount = trim(filter_var($_POST['insurance_in_amount'],FILTER_SANITIZE_MAGIC_QUOTES));
	$documents = trim(filter_var($_POST['documents'],FILTER_SANITIZE_MAGIC_QUOTES));
	$info = trim(filter_var($_POST['info'],FILTER_SANITIZE_MAGIC_QUOTES));
	$edit_query = "update `auto` set `bank_id`='$bank',`regionally`='$regionally',`name`='$name',`seller`='$seller',`vehicle_type`='$vehicle_type',`initial_fee`='$initial_fee',`delivery_commission`='$delivery_commission',`service_commission`='$service_commission',`early_repayment`='$early_repayment',`er_commission`='$er_commission',`Insurance`='$insurance',`insurance_in_amount`='$insurance_in_amount',`documents`='$documents',`info`='$info' where `auto_id` = '$_POST[auto_id]' limit 1";
	if (!$cur_error)
	{
		if (mysql_query($edit_query))
		{
			if (isset($_POST['RUB']))
			{
				$rub_res = mysql_query("select * from `credit_currency` where `credit_id` = '$_POST[auto_id]' and `type` = '2' and `currency` = 'RUB'");
				if (mysql_num_rows($rub_res) > 0)
					$rub_query = "update `credit_currency` set `sum_low`='$_POST[RUB_sum_low]',`sum_high`='$_POST[RUB_sum_high]',`period_low`='$_POST[RUB_period_low]',`period_high`='$_POST[RUB_period_high]',`rate_low`='$_POST[RUB_rate_low]',`rate_high`='$_POST[RUB_rate_high]' where `credit_id` = '$_POST[auto_id]' and `type` = '2' and `currency` = 'RUB' limit 1";
				else
					$rub_query = "insert into `credit_currency` (`credit_id`,`type`,`currency`,`sum_low`,`sum_high`,`period_low`,`period_high`,`rate_low`,`rate_high`) values ('$_POST[auto_id]','2','RUB','$_POST[RUB_sum_low]','$_POST[RUB_sum_high]','$_POST[RUB_period_low]','$_POST[RUB_period_high]','$_POST[RUB_rate_low]','$_POST[RUB_rate_high]')";
				mysql_query($rub_query);
			}
			else
				mysql_query("delete from `credit_currency` where `credit_id` = '$_POST[auto_id]' and `type` = '2' and `currency` = 'RUB' limit 1");
			if (isset($_POST['USD']))
			{
				$usd_res = mysql_query("select * from `credit_currency` where `credit_id` = '$_POST[auto_id]' and `type` = '2' and `currency` = 'USD'");
				if (mysql_num_rows($usd_res) > 0)
					$usd_query = "update `credit_currency` set `sum_low`='$_POST[USD_sum_low]',`sum_high`='$_POST[USD_sum_high]',`period_low`='$_POST[USD_period_low]',`period_high`='$_POST[USD_period_high]',`rate_low`='$_POST[USD_rate_low]',`rate_high`='$_POST[USD_rate_high]' where `credit_id` = '$_POST[auto_id]' and `type` = '2' and `currency` = 'USD' limit 1";
				else
					$usd_query = "insert into `credit_currency` (`credit_id`,`type`,`currency`,`sum_low`,`sum_high`,`period_low`,`period_high`,`rate_low`,`rate_high`) values ('$_POST[auto_id]','2','USD','$_POST[USD_sum_low]','$_POST[USD_sum_high]','$_POST[USD_period_low]','$_POST[USD_period_high]','$_POST[USD_rate_low]','$_POST[USD_rate_high]')";
				mysql_query($usd_query);
			}
			else
				mysql_query("delete from `credit_currency` where `credit_id` = '$_POST[auto_id]' and `type` = '2' and `currency` = 'USD' limit 1");
			if (isset($_POST['EUR']))
			{
				$eur_res = mysql_query("select * from `credit_currency` where `credit_id` = '$_POST[auto_id]' and `type` = '2' and `currency` = 'EUR'");
				if (mysql_num_rows($eur_res) > 0)
					$eur_query = "update `credit_currency` set `sum_low`='$_POST[EUR_sum_low]',`sum_high`='$_POST[EUR_sum_high]',`period_low`='$_POST[EUR_period_low]',`period_high`='$_POST[EUR_period_high]',`rate_low`='$_POST[EUR_rate_low]',`rate_high`='$_POST[EUR_rate_high]' where `credit_id` = '$_POST[auto_id]' and `type` = '2' and `currency` = 'EUR' limit 1";
				else
					$eur_query = "insert into `credit_currency` (`credit_id`,`type`,`currency`,`sum_low`,`sum_high`,`period_low`,`period_high`,`rate_low`,`rate_high`) values ('$_POST[auto_id]','2','EUR','$_POST[EUR_sum_low]','$_POST[EUR_sum_high]','$_POST[EUR_period_low]','$_POST[EUR_period_high]','$_POST[EUR_rate_low]','$_POST[EUR_rate_high]')";
				mysql_query($eur_query);
			}
			else
				mysql_query("delete from `credit_currency` where `credit_id` = '$_POST[auto_id]' and `type` = '2' and `currency` = 'EUR' limit 1");
		}
		else
			$add_error = true;
	}
	else
		$add_error = true;
}
if ($auto_id)
{
	$auto_res = mysql_query("select * from `auto` where `auto_id` = '$auto_id' limit 1");
	
	if (mysql_num_rows($auto_res) == 0) {
		to("/admin/credits/auto/");
	}
	
	$auto_row = mysql_fetch_array($auto_res);
	
	$city_path = $db->getCell("select `C`.`path` from `city` as `C`,`bank` as `B` where `B`.`bank_id` = '$auto_row[bank_id]' and `B`.`city_id` = `C`.`city_id` limit 1");
}

require_once ADMIN.HEADFILE;
?>
<script type="text/javascript" src="/files/js/admin/currency.js"></script>
<script type="text/javascript">
$(document).ready(function(){
	$("#bank").change(function(){
		if ($("#bank option:selected").hasClass("branch")) {
			$("#regionally").attr("disabled","disabled").removeAttr("checked");
		} else {
			$("#regionally").removeAttr("disabled");
		}
	})
})
</script>
<div align="left">
<h1>Редактирование кредита (На авто)</h1>
<hr /><?php
if (isset($_POST['action']) && $_POST['action'] == "edit" && !$edit_error)
	echo "<p style='color:green'>Успешно отредактировано</p>";
elseif ($cur_error)
	echo "<p style='color:red'>Необходимо указать данные хотя бы для одной валюты</p>";
elseif ($edit_error)
	echo "<p style='color:red'>Не удалось отредактировать</p>";
?><form method='POST'>
<input type='hidden' name='action' value='edit' />
<input type='hidden' name='auto_id' value='<?php echo $auto_row['auto_id']; ?>' />
<?php
$cur_res = mysql_query("select * from `credit_currency` where `credit_id` = '$auto_id' and `type` = '2';");
require_once ACREDITS."edit_credit_currency.php";
?>
<table cellpadding='5' cellspacing='0'>
	<tr>
		<td width="200px">Ссылка на сайте</td>
		<td width="500px">
			<a href='<?php echo "/$city_path/credits/auto/".$auto_row['auto_id'];?>' target="_blank"><?php echo $auto_row['name'];?></a>
		</td>
	</tr>
	<tr>
		<td>ID</td>
		<td><input style="width:200px" type='text' name='auto_id' value='<?php echo $auto_row['auto_id'];?>' disabled /></td>
	</tr>
	<tr>
		<td>Название</td>
		<td><input style='width:100%' type='text' name='name' value='<?php echo $auto_row['name'];?>' /></td>
	</tr>
	<tr>
		<td>Банк</td>
		<td>
			<select style="width:200px" name='bank' id='bank'>
				<?php
				$bankslist = $db->getTable("select `bank_id`,`name` from `bank` where `parent` = '0' order by `name`");
				echo "<option disabled='disabled' style='color:gray'>———————————————</option>
						<option disabled='disabled' style='color:gray'>Головные офисы</option>
						<option disabled='disabled' style='color:gray'>———————————————</option>";
				if ($bankslist) {
					
					foreach ($bankslist as $bank) {
						
						echo "<option value='$bank[bank_id]'";
						if ($bank['bank_id'] == $auto_row['bank_id'])
							echo " selected='selected'";
						echo ">$bank[name]</option>";
					}
				} else {
					echo "<option disabled='disabled' style='color:gray'>В данном городе нет головных офисов</option>";
				}
				$branches = $db->getTable("select `bank_id`,`name` from `bank` where `parent` != '0' and `city_id` = '$_SESSION[city_admin]' order by `name`");
				echo "<option disabled='disabled' style='color:gray'>———————————————</option>
						<option disabled='disabled' style='color:gray'>Филиалы</option>
						<option disabled='disabled' style='color:gray'>———————————————</option>";
				$regional = false;
				if ($branches) {
					
					foreach ($branches as $branch) {
						
						echo "<option class='branch' value='$branch[bank_id]'";
						if ($branch['bank_id'] == $auto_row['bank_id']) {
							echo " selected='selected'";
							$regional = true;
						}
						echo ">$branch[name]</option>";
					}
				} else {
					echo "<option disabled='disabled' style='color:gray'>В данном городе нет филиалов</option>";
				}
				?>
			</select>
		</td>
	</tr>
	<tr>
		<td>Межрегионально</td>
		<td colspan='2' align="left">
			<input type='checkbox' name='regionally' id='regionally' <?php
				if ($auto_row['regionally']) {
					echo "checked='checked'";
				}
				if ($regional) {
					echo "disabled='disabled'";
				}
			?> />
		</td>
	</tr>
	<tr>
		<td>Продавец</td>
		<td>
			<input style='width:100%' type='text' name='seller' value='<?php echo $auto_row['seller'];?>' />
		</td>
	</tr>
	<tr>
		<td>Вид транспортного средства</td>
		<td>
			<input style='width:100%' type='text' name='vehicle_type' value='<?php echo $auto_row['vehicle_type'];?>' />
		</td>
	</tr>
	<tr>
		<td>Минимальный первоначальный взнос (%)</td>
		<td>
			<input style='width:200px' type='text' name='initial_fee' value='<?php echo $auto_row['initial_fee'];?>' />
		</td>
	</tr>
	<tr>
		<td>Комиссия за выдачу (%)</td>
		<td>
			<input style='width:200px' type='text' name='delivery_commission' value='<?php echo $auto_row['delivery_commission']; ?>' />
		</td>
	</tr>
	<tr>
		<td>Комиссия за обслуживание (%)</td>
		<td>
			<input style='width:200px' type='text' name='service_commission' value='<?php echo $auto_row['service_commission']; ?>' />
		</td>
	</tr>
	<tr>
		<td>Возможность досрочного погашения</td>
		<td>
			<input type='checkbox' name='early_repayment'<?php
				if ($auto_row['early_repayment'])
					echo " checked='checked'";
			?> />
		</td>
	</tr>
	<tr>
		<td>Комиссия за досрочное погашение (%)</td>
		<td>
			<input style='width:100%' type='text' name='er_commission' value='<?php echo $auto_row['er_commission']; ?>' />
		</td>
	</tr>
	<tr>
		<td>Страховка</td>
		<td>
			<input style='width:100%' type='text' name='insurance' value='<?php echo $auto_row['Insurance']; ?>' />
		</td>
	</tr>
	<tr>
		<td>Включение страховки в сумму кредита</td>
		<td>
			<input style='width:100%' type='text' name='insurance_in_amount' value='<?php echo $auto_row['insurance_in_amount']; ?>' />
		</td>
	</tr>
	<tr>
		<td>Документы</td>
		<td>
			<input style='width:100%' type='text' name='documents' value='<?php echo $auto_row['documents']; ?>' />
			<br /><span style='color:gray;font-size:8pt'>Список документов через запятую</span>
		</td>
	</tr>
	<tr valign='top'>
		<td>Инфо</td>
		<td><textarea style='width:100%' rows='5' name='info' id='info'><?php echo $auto_row['info']; ?></textarea></td>
	</tr>
	<tr valign='top'>
		<td colspan='2'>
			<p><input type='button' id="insert_city" value='Вставить' /> - Вставить название города<br />
			<input type='button' id="insert_city_rod" value='Вставить' /> - Вставить название города в родительном падеже<br />
			<input type='button' id="insert_city_pred" value='Вставить' /> - Вставить название города в предложном падеже<br />
			</p>
		</td>
	</tr>
	<tr valign='top'>
		<td colspan='2' align="right"><button style="width:100px;height:30px" type="submit">Сохранить</button></td>
	</tr>
</table>
</form>
<br /><hr /><br />
</div>